import json
import logging
import os
import random
from datetime import datetime

from product_upload.develop_third.aws_list_all_key import aws_upload_img_to_s3
from product_upload.develop_third.aws_util import aws_ocr_new_product
from product_upload.domain.basic.basic_brand import BasicBrand
from product_upload.domain.basic.basic_image import BasicImage
from product_upload.domain.basic.basic_product import BasicProduct
from product_upload.util.basic.mysql_util import db_list_by_page, db_batch_update, db_batch_insert
from product_upload.util.seller.amazon_us_new_util import save_json_to_redis
from product_upload.util.seller.amazon_us_util import OLD_AMAZON_US_COMMON_KEY_PREFIX

logger = logging.getLogger(__name__)


# 还是老模板，todo
def basic_brand_sensitive_to_write_json_file():
    db_brand_list = db_list_by_page("basic_brand", "origin,name", "status = 1", BasicBrand, 1, 99999999)
    update_dict = {
        "need_filter_field": ["item_name", "product_description", "bullet_point1", "bullet_point2", "bullet_point3",
                              "bullet_point4", "bullet_point5", "model_name", "generic_keywords"]}
    for db_brand in db_brand_list:
        tmp_list = update_dict.get(db_brand.origin, [])
        if db_brand.name:
            tmp_list.append(db_brand.name)
            if " " in db_brand.name:
                tmp_list.append(db_brand.name.replace(" ", "-"))
            if "-" in db_brand.name:
                tmp_list.append(db_brand.name.replace("-", " "))
            tmp_list = list(set(tmp_list))
            update_dict.update({db_brand.origin: tmp_list})
    user_directory = os.path.join(os.path.expanduser("~"), 'Desktop')
    try:
        with open(f"{user_directory}\\amazon_rule\\json\\sensitive.json", 'w', encoding='utf-8') as json_file:
            json.dump(update_dict, json_file, indent=4, ensure_ascii=False)
    except Exception as e:
        logger.error(e)
    try:
        success = save_json_to_redis(OLD_AMAZON_US_COMMON_KEY_PREFIX, "sensitive", update_dict)
        if success:
            logger.info("Successfully updated sensitive brands in Redis")
        else:
            logger.error("Failed to update sensitive brands in Redis")
    except Exception as e:
        logger.error(f"Error updating sensitive brands in Redis: {e}")


# 新字段还未启用
# def basic_brand_sensitive_to_write_json_file():
#     db_brand_list = db_list_by_page("basic_brand", "origin,name", "status = 1", BasicBrand, 1, 99999999)
#     update_dict = {
#         "need_filter_field": ["item_name", "product_description", "bullet_point#1.value", "bullet_point#2.value", "bullet_point#3.value",
#                               "bullet_point#4.value", "bullet_point#5.value", "model_name", "generic_keywords"]}
#     for db_brand in db_brand_list:
#         tmp_list = update_dict.get(db_brand.origin, [])
#         if db_brand.name:
#             tmp_list.append(db_brand.name)
#             if " " in db_brand.name:
#                 tmp_list.append(db_brand.name.replace(" ", "-"))
#             if "-" in db_brand.name:
#                 tmp_list.append(db_brand.name.replace("-", " "))
#             tmp_list = list(set(tmp_list))
#             update_dict.update({db_brand.origin: tmp_list})
#     try:
#         success = save_json_to_redis(AMAZON_US_COMMON_KEY_PREFIX, "sensitive", update_dict)
#         if success:
#             print("Successfully updated sensitive brands in Redis")
#         else:
#             print("Failed to update sensitive brands in Redis")
#     except Exception as e:
#         print(f"Error updating sensitive brands in Redis: {e}")


# 同步检查的image到product,在启动制作表格的时候调用
def sync_image_to_product(platform=None, basic_id=None):
    condition = "1=1"
    if platform:
        condition += f" and platform = '{platform}'"
        logger.info('start basic image to product.....')
    if basic_id:
        condition += f" and basic_id = {basic_id}"
    for page in range(1, 9999):
        basic_image_list = db_list_by_page("basic_image", ",".join(BasicImage.fields), condition, BasicImage, page,
                                           50000)
        if not basic_image_list:
            break
        update_image_dict = {}
        for basic_image in basic_image_list:
            basic_id = basic_image.basic_id
            status = basic_image.status
            main_image = basic_image.main_image
            img_list = [basic_image.main_image, basic_image.other_image_url1, basic_image.other_image_url2,
                        basic_image.other_image_url3, basic_image.other_image_url4, basic_image.other_image_url5,
                        basic_image.other_image_url6, basic_image.other_image_url7, basic_image.other_image_url8,
                        basic_image.other_image_url9, basic_image.other_image_url10, basic_image.other_image_url11,
                        basic_image.other_image_url12, basic_image.other_image_url13, basic_image.other_image_url14,
                        basic_image.other_image_url15]
            img_list = [x for x in img_list if x]
            if len(img_list) >= 2:
                if basic_image.ocr_result and basic_image.ocr_result.startswith("{"):
                    ocr_json = json.loads(basic_image.ocr_result)
                    if ocr_json.get("inch_url") and ocr_json.get("inch_url")[0] in img_list:
                        inch_url = ocr_json.get("inch_url")[0]
                        original_index = img_list.index(inch_url)
                        # 如果inch_url已经在第二位，则不需要交换
                        if original_index != 1:
                            # 保存原来的第二个元素
                            second_item = img_list[1]
                            # 将inch_url移到第二位
                            img_list[1] = inch_url
                            # 将原来的第二个元素移动到inch_url原来的位置
                            img_list[original_index] = second_item
            update_image_dict[basic_id] = {"main_image": main_image, "img_list": img_list, "status": status,
                                           "image_count": len(img_list)}
        ids = ",".join([str(x) for x in list(update_image_dict.keys())])
        db_product_list = db_list_by_page("basic_product", "id,json_text", f"id in ({ids})", BasicProduct, 1, 99999999)
        update_product = []
        for db_prod in db_product_list:
            if db_prod.json_text is not None:
                json_text = json.loads(db_prod.json_text)
                status = update_image_dict.get(db_prod.id).get("status")
                img_list = update_image_dict.get(db_prod.id).get("img_list")
                image_count = len(img_list)
                json_text["images_list"] = img_list
                main_image = img_list[0] if len(img_list) > 0 else ""
                json_text["main_image"] = main_image
                update_product.append([db_prod.id, status, main_image, json.dumps(json_text), image_count])
        db_batch_update("basic_product", ["id", "status", "main_image", "json_text", "image_count"], update_product)
    if platform:
        logger.info('end basic image to product.....')


# 删除amazon_us上传失败的记录,有3天的缓冲期.也就是db需要3天前,而亚马逊后台导出数据是选今天往前面推一周
def sync_delete_amazon_us_record_upload_fail():
    # 已经由java实现
    pass


# 包括把basic_gg的新品追加到basic_product中和 XL GG 新品上传S3 和 对 GG进行OCR识别
def basic_sync_product_to_image_to_s3_ocr():
    # GG主表产品添加到维护表
    basic_sync_info_product_to_image("GG")
    # GG去S3
    aws_upload_img_to_s3("GG")
    # GG S3图片同步回主表
    sync_image_to_product("GG", None)
    # XL主表产品添加到维护表
    basic_sync_info_product_to_image("XL")
    # XL去S3
    aws_upload_img_to_s3("XL")
    # s3图片同步回主表
    sync_image_to_product("XL", None)
    # DB主表产品添加到维护表
    basic_sync_info_product_to_image("DB")
    # DB去S3
    aws_upload_img_to_s3("DB")
    # s3图片同步回主表
    sync_image_to_product("DB", None)
    # GG去OCR
    # 自动OCR暂时注释
    # aws_ocr_new_product("GG")
    # ocr图片同步回主表
    # sync_image_to_product("GG", None)
    # DB去OCR
    # aws_ocr_new_product("DB")
    # ocr图片同步回主表
    # sync_image_to_product("DB", None)


# 新品同步基础表的内容到维护表
def basic_sync_info_product_to_image(platform):
    # 只rpa走了product_type新类型的再同步到image中
    conditions = f'platform="{platform}" and published = 1 and product_type !="" and not_available not like "%amazon%" and quantity > 3 and class_name not in ("Clothes & Decoration", "Jewelry","Automotive","Media products - books DVD Music software video") and product_type not in ("wallart","WALL_ART") and id not in (select basic_id from basic_image)'
    basic_product_id_list = db_list_by_page("basic_product", "id", conditions, BasicProduct, 1, 99999999)
    product_id_list = [str(tmp_prod.id) for tmp_prod in basic_product_id_list]
    logger.info(f"need move basic to image size:{len(product_id_list)}")
    if len(product_id_list) > 0:
        create_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        for limit_size in range(0, len(product_id_list), 10000):
            limit_id_list = product_id_list[limit_size: limit_size + 10000]
            ids = ",".join(limit_id_list)
            basic_product_list = db_list_by_page("basic_product",
                                                 "id,status,published,sku,title,platform,class_name,product_type,json_text",
                                                 f"id in ({ids})", BasicProduct, 1, 99999999)
            item_list = []
            for basic_product in basic_product_list:
                image_item = [basic_product.id, create_time, 1, basic_product.status, basic_product.published,
                              basic_product.sku, basic_product.title, basic_product.platform, basic_product.class_name,
                              basic_product.product_type]
                json_obj = json.loads(basic_product.json_text) if basic_product.json_text else {}
                images_list = json_obj.get("images_list", [])
                images_list = [x for x in images_list if x and ".gif" not in x]
                img_list = images_list + (16 - len(images_list)) * ['']
                image_item.extend(img_list[0:16])
                item_list.append(image_item)
            db_batch_insert("basic_image",
                            ["basic_id", "create_time", "ocr_status", "status", "published", "sku", "title", "platform",
                             "class_name", "product_type", "main_image", "other_image_url1", "other_image_url2",
                             "other_image_url3", "other_image_url4", "other_image_url5",
                             "other_image_url6", "other_image_url7", "other_image_url8", "other_image_url9",
                             "other_image_url10", "other_image_url11", "other_image_url12", "other_image_url13",
                             "other_image_url14", "other_image_url15"], item_list)


def get_amazon_us_config_price_strategy():
    sprice_strategy_tuple = db_list_by_page("sys_config", "config_value", 'config_key = "amazon_us_price_strategy"',
                                            None, 1, 10, "config_id")
    if not sprice_strategy_tuple:
        return {}
    return json.loads(sprice_strategy_tuple[0][0])


# 计算价格根据各种品类
def get_prod_price_by_class_name(cost, class_name, price_strategy):
    cal_price = round(calculate_price(cost, class_name, price_strategy), 2)
    final_price = random_price(cal_price)
    return final_price if final_price > 0 else 0


def calculate_price(cost, class_name, price_strategy):
    if class_name not in price_strategy:
        class_name = "Others"
    strategy = price_strategy[class_name]
    if strategy["type"] == "fixed_ratio":
        denominator = float(strategy["formula"].split("/")[1])
        return cost / denominator
    elif strategy["type"] == "tiered":
        for tier in strategy["tiers"]:
            min_cost = tier.get("min", 0)
            max_cost = tier.get("max", float('inf'))
            if min_cost <= cost <= max_cost:
                formula = tier["formula"]
                if "+" in formula:
                    # 处理带加法的公式，如 (cost+21)/0.7
                    parts = formula.replace("(", "").replace(")", "").split("/")
                    add_parts = parts[0].split("+")
                    add_value = float(add_parts[1])
                    denominator = float(parts[1])
                    return (cost + add_value) / denominator
                else:
                    # 处理简单除法公式，如 cost/0.63
                    denominator = float(formula.split("/")[1])
                    return cost / denominator


def random_price(value):
    base_jitter = random.choice([round(i * 0.01, 2) for i in range(1, 51)])
    if random.random() < 1 / 2:
        jitter = -base_jitter  # 降价
    else:
        jitter = base_jitter  # 涨价
    return round(value + jitter, 2)


if __name__ == '__main__':
    basic_sync_product_to_image_to_s3_ocr()
    aws_ocr_new_product("GG")
    sync_image_to_product("GG", None)
    aws_ocr_new_product("DB")
    sync_image_to_product("DB", None)
    pass
